﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ShiftSchedulingManagementDto;
using ThridGroup.ERP.ProductionSystem;

namespace ThridGroup.ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 排班管理控制器
    /// </summary>
    public class ShiftSchedulingManagementController : Controller
    {
        /// <summary>
        /// 班组设置接口
        /// </summary>
        private readonly ITeamServices _teamServices;
        
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="teamServices">班组设置接口</param>
        public ShiftSchedulingManagementController(ITeamServices teamServices)
        {
            _teamServices = teamServices;
        }


        /// <summary>
        /// 班组管理视图
        /// </summary>
        /// <returns></returns>
        public IActionResult ShowTeamManagementView()
        {
            return View();
        }

        /// <summary>
        /// 添加班组管理视图
        /// </summary>
        /// <returns></returns>
        public IActionResult CreateTeamManagementView()
        {
            return View();
        }

        /// <summary>
        /// 修改班组管理视图
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdateTeamManagementView()
        {
            return View();
        }

        /// <summary>
        /// 添加班组
        /// </summary>
        /// <param name="dto">班组信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateTeam([FromBody] TeanListDto dto)
        {
            try
            {
                // 手动验证模型状态
                if (!ModelState.IsValid)
                {
                    var errors = ModelState
                        .Where(x => x.Value.Errors.Count > 0)
                        .Select(x => new { Field = x.Key, Errors = x.Value.Errors.Select(e => e.ErrorMessage) });
                    
                    return BadRequest(new { message = "模型验证失败", errors = errors });
                }

                // 手动验证必填字段
                if (string.IsNullOrWhiteSpace(dto?.TeamNumber))
                {
                    return BadRequest(new { message = "班组编号不能为空" });
                }
                if (string.IsNullOrWhiteSpace(dto?.TeamName))
                {
                    return BadRequest(new { message = "班组名称不能为空" });
                }
                if (string.IsNullOrWhiteSpace(dto?.TeamType))
                {
                    return BadRequest(new { message = "班组类型不能为空" });
                }

                var result = await _teamServices.CreateTeam(dto);
                
                if (result > 0)
                {
                    return Ok(new { success = true, message = "添加成功", result = result });
                }
                else
                {
                    return BadRequest(new { success = false, message = "添加失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, message = "服务器错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 显示班组信息（分页查询）
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> QueryTeam([FromQuery] GetTeamDto dto)
        {
            var list = await _teamServices.QueryTeam(dto);
            
           
            
            var teamList = list.OrderByDescending(a => a.Id)
                .Skip((dto.page - 1) * dto.limit)
                .Take(dto.limit)
                .ToList();

            return Json(new
            {
                code = 0,
                msg = "",
                count = list.Count,
                data = teamList
            });
        }

        /// <summary>
        /// 回显单条班组信息
        /// </summary>
        /// <param name="id">班组ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<TeanListDto> GetTeamById(int id)
        {
            return await _teamServices.GetTeamById(id);
        }

      

        /// <summary>
        /// 批量删除班组信息
        /// </summary>
        /// <param name="ids">要删除的班组ID列表</param>
        /// <returns></returns>
        [HttpPost]
        public async Task BatchDelTeam([FromBody] List<int> ids)
        {
            await _teamServices.BatchDeleteTeam(ids);
        }

        /// <summary>
        /// 修改班组信息
        /// </summary>
        /// <param name="dto">班组信息</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateTeam([FromBody] TeanListDto dto)
        {
            try
            {
                // 手动验证模型状态
                if (!ModelState.IsValid)
                {
                    var errors = ModelState
                        .Where(x => x.Value.Errors.Count > 0)
                        .Select(x => new { Field = x.Key, Errors = x.Value.Errors.Select(e => e.ErrorMessage) });
                    
                    return BadRequest(new { message = "模型验证失败", errors = errors });
                }

                // 手动验证必填字段
                if (string.IsNullOrWhiteSpace(dto?.TeamNumber))
                {
                    return BadRequest(new { message = "班组编号不能为空" });
                }
                if (string.IsNullOrWhiteSpace(dto?.TeamName))
                {
                    return BadRequest(new { message = "班组名称不能为空" });
                }
                if (string.IsNullOrWhiteSpace(dto?.TeamType))
                {
                    return BadRequest(new { message = "班组类型不能为空" });
                }

                var result = await _teamServices.UpdateTeam(dto);
                
                if (result > 0)
                {
                    return Ok(new { success = true, message = "修改成功", result = result });
                }
                else
                {
                    return BadRequest(new { success = false, message = "修改失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, message = "服务器错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 导出班组信息到Excel
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <param name="exportAll">是否导出全部</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportExcel([FromQuery] GetTeamDto dto, bool exportAll = false)
        {
            try
            {
                byte[] data = null;
                string contentType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
                string fileName = "导出班组管理信息.xlsx";

                // 新建工作簿
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                IRow headerRow = sheet.CreateRow(0);

                // 设置表头
                headerRow.CreateCell(0).SetCellValue("班组编号");
                headerRow.CreateCell(1).SetCellValue("班组名称");
                headerRow.CreateCell(2).SetCellValue("班组类型");
                headerRow.CreateCell(3).SetCellValue("备注");

                // 获取数据
                var list = await _teamServices.QueryTeam(dto);

                // 判断是否导出全部
                var exportList = exportAll
                    ? list.OrderByDescending(a => a.Id).ToList()
                    : list.OrderByDescending(a => a.Id)
                          .Take(100) // 默认最多导出100条
                          .ToList();

                int index = 1;
                foreach (var item in exportList)
                {
                    IRow row = sheet.CreateRow(index);
                    row.CreateCell(0).SetCellValue(item.TeamNumber ?? "");
                    row.CreateCell(1).SetCellValue(item.TeamName ?? "");
                    row.CreateCell(2).SetCellValue(item.TeamType ?? "");
                    row.CreateCell(3).SetCellValue(item.Descr ?? "");
                    index++;
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    data = ms.ToArray();
                }

                return File(data, contentType, fileName);
            }
            catch (Exception ex)
            {
                return Content("导出失败：" + ex.Message);
            }
        }
    }
}
